//
// GPSMapEdit
// (c) Konstantin Galichsky (kg@geopainting.com), 2006
//
// The helper to show dialog with listbox.
//

# include "StdAfx.h"
# include "Resource.h"
# include "SelectList.h"
# include "Dialog.h"
# include "ListView.h"
# include "Globals.h"

class CSelectFromList : public CDialog {
  public:
	CSelectFromList (UINT _uiTitle, const CListBoxItem * _lbd, size_t _cItems, int & _nCode) :
		CDialog (IDD_SELECT_FROM_LIST),
		m_uiTitle (_uiTitle),
		m_lbd (_lbd),
		m_cItems (_cItems),
		m_nCode (_nCode)
	{}

	// Override.
	virtual bool OnInit (HWND _hwndFocus);
	virtual void OnCommand (WORD _wCmd, WORD _wNotifyCode, HWND _hwndCtl);
	virtual bool OnNotify (int _idCtrl, NMHDR * _pInfo);

  private:
	const UINT m_uiTitle;
	const CListBoxItem * const m_lbd;
	const size_t m_cItems;
	int & m_nCode;

	HWND m_hList;
};

bool CSelectFromList::OnInit (HWND _hwndFocus) {
	// Title.
	char strTitle [64];
	LoadString (m_uiTitle, strTitle, sizeof (strTitle)/sizeof (strTitle [0]));
	SetWindowText (m_hWnd, strTitle);

	// List.
	m_hList = GetDlgItem (IDC_LIST);
	AddColumn (m_hList, 0, strTitle);

	for (size_t c = 0; c < m_cItems; ++ c) {
		char strItem [64];
		LoadString (m_lbd [c].uiText, strItem, sizeof (strItem)/sizeof (strItem [0]));
		InsertItem (m_hList, c, m_lbd [c].nCode, "%s", strItem);

		if (m_lbd [c].nCode == m_nCode)
			SetSelection (m_hList, c);
	}
	AutoSizeColumns (m_hList);

	EnsureSelectionVisible (m_hList);

	// OK.
	EnableDlgItem (IDOK, false);

	return true;
}

void CSelectFromList::OnCommand (WORD _wCmd, WORD _wNotifyCode, HWND _hwndCtl) {
	switch (_wCmd) {
		case IDOK: {
			const size_t cSel = ListView_GetSelectionMark (m_hList);
			if (cSel != -1) {
				m_nCode = GetLParam (m_hList, cSel);
				EndDialog (0);
			} else
				EndDialog (1);
			break;
		}

		case IDCANCEL:
			EndDialog (1);
			break;
	}
}

bool CSelectFromList::OnNotify (int _idCtrl, NMHDR * _pInfo) {
	switch (_pInfo->code) {
		case NM_CLICK:
		case LVN_KEYDOWN:
			if (_idCtrl == IDC_LIST)
				EnableDlgItem (IDOK, true);
			break;

		case NM_RETURN:
		case NM_DBLCLK:
			if (_idCtrl == IDC_LIST)
				SendCommand (IDOK);
			break;
	}

	return CDialog::OnNotify (_idCtrl, _pInfo);
}

bool SelectFromList (HWND _hWnd, UINT _uiTitle, const CListBoxItem * _lbd, size_t _cItems, int & _nCode) {
	CSelectFromList sld (_uiTitle, _lbd, _cItems, _nCode);
	return sld.ShowModal (_hWnd) == 0;
}
